from django.db import models

# Create your models here.

"""
SCL-90心理健康评估数据模型

由于MVP版本不使用数据库，这里定义的是普通Python类作为数据结构
"""
import uuid
from datetime import datetime
from typing import Dict, Optional, Any
from dataclasses import dataclass, field
import json


@dataclass
class BasicInfo:
    """用户基本信息"""
    age: str  # 年龄范围
    gender: str  # 性别
    occupation: str  # 职业
    sleep_condition: str  # 睡眠状况
    
    def validate(self) -> bool:
        """验证基本信息"""
        valid_ages = ['18岁以下', '18-25岁', '26-35岁', '36-45岁', '46-55岁', '56-65岁', '65岁以上']
        valid_genders = ['男', '女', '其他']
        valid_occupations = ['学生', '教师', '医护人员', '企业员工', '公务员', '个体经营', '退休人员', '无业/待业', '其他']
        valid_sleep = ['睡眠质量很好', '偶尔失眠', '经常失眠', '严重失眠', '需要药物辅助睡眠']
        
        return (self.age in valid_ages and 
                self.gender in valid_genders and 
                self.occupation in valid_occupations and 
                self.sleep_condition in valid_sleep)


@dataclass 
class SCLAnswers:
    """SCL-90问卷答案"""
    answers: Dict[str, int] = field(default_factory=dict)  # 题目ID -> 分数(1-5)
    
    def validate(self) -> bool:
        """验证答案数据"""
        # 检查题目数量
        if len(self.answers) != 90:
            return False
        
        # 检查题目编号
        expected_questions = set(str(i) for i in range(1, 91))
        if set(self.answers.keys()) != expected_questions:
            return False
        
        # 检查分数范围
        for score in self.answers.values():
            if not isinstance(score, int) or score < 1 or score > 5:
                return False
        
        return True
    
    def get_score(self, question_id: str) -> int:
        """获取题目分数"""
        return self.answers.get(question_id, 0)


@dataclass
class AssessmentResult:
    """评估结果"""
    test_id: str
    total_score: int  # 总分 (90-450)
    average_score: float  # 平均分 (1.0-5.0)
    analysis_report: str
    recommendations: str
    risk_level: str
    short_url: str
    created_at: datetime
    basic_info: BasicInfo
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典用于API响应"""
        return {
            'test_id': self.test_id,
            'total_score': self.total_score,
            'average_score': self.average_score,
            'analysis_report': self.analysis_report,
            'recommendations': self.recommendations,
            'risk_level': self.risk_level,
            'short_url': self.short_url,
            'created_at': self.created_at.isoformat(),
        }


@dataclass
class AssessmentData:
    """完整的评估数据"""
    test_id: str
    basic_info: BasicInfo
    scl_answers: SCLAnswers
    timestamp: datetime
    result: Optional[AssessmentResult] = None
    
    def __post_init__(self):
        """初始化后处理"""
        if isinstance(self.timestamp, str):
            self.timestamp = datetime.fromisoformat(self.timestamp)
    
    def validate(self) -> bool:
        """验证完整数据"""
        return (self.basic_info.validate() and 
                self.scl_answers.validate() and
                bool(self.test_id))
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'test_id': self.test_id,
            'basic_info': {
                'age': self.basic_info.age,
                'gender': self.basic_info.gender,
                'occupation': self.basic_info.occupation,
                'sleep_condition': self.basic_info.sleep_condition,
            },
            'scl_answers': self.scl_answers.answers,
            'timestamp': self.timestamp.isoformat(),
        }


def generate_test_id() -> str:
    """生成测试ID"""
    return str(uuid.uuid4())


def get_risk_level(total_score: int) -> str:
    """根据总分确定风险等级"""
    if total_score <= 180:
        return '正常'
    elif total_score <= 270:
        return '轻度困扰'
    elif total_score <= 360:
        return '中度困扰'
    elif total_score <= 405:
        return '较重困扰'
    else:
        return '严重困扰'
